import gulp from 'gulp';
import esbuild from 'gulp-esbuild';
import browserSync from 'browser-sync';
import { deleteAsync } from 'del';
const bs = browserSync.create();

const paths = {
  pages: ['src/*.html'],
  ts: ['src/**/*.ts']
};

// Copy HTML files
const copyHtml = () => {
  return gulp.src(paths.pages)
    .pipe(gulp.dest("dist"));
}

// Bundle TypeScript files
const build = () => {
  return gulp.src('src/main.ts')
    .pipe(esbuild({
      bundle: true,
      minify: true,
      sourcemap: true,
      target: ['es2015'],
      outfile: 'bundle.js',
      format: 'esm', // 确保输出 ES modules
    }))
    .on('error', (err) => {
      console.error(err);
      this.emit('end'); // 处理错误
    })
    .pipe(gulp.dest("dist"));
}

// Clear dist directory
const clear = () => deleteAsync(['dist/**/*']);

// Watch for changes
const watch = () => {
  bs.init({
    server: {
      baseDir: './dist'
    }
  });
  gulp.watch(paths.ts, gulp.series(build, bs.reload));
  gulp.watch(paths.pages, gulp.series(copyHtml, bs.reload));
}

// Define tasks 
gulp.task("clear", clear);
gulp.task("copy-html", copyHtml);
gulp.task("build", build);
gulp.task("watch", watch);
gulp.task("default", gulp.series(clear, gulp.parallel(build, copyHtml), watch));


